package fun.codedesign.principle.advice151.a131;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 栅栏在其他线程运行完成后执行 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-10 9:29
 * @since 1.0.0
 */
public class CyclicBarrierApp {
    @Test
    public void test() throws InterruptedException {
        // final CyclicBarrier barrier = new CyclicBarrier(2);
        final CyclicBarrier barrier1 = new CyclicBarrier(2, new Runnable() {
            @Override
            public void run() {
                System.out.println("所有线程已执行");

            }
        });

        new Thread() {
            @Override
            public void run() {
                System.out.println("线程一执行");
                try {
                    barrier1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                System.out.println("线程二执行");
                try {
                    barrier1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        Thread.sleep(3000);

        // 如果以上的程序在test程序结束时中断会抛出异常

    }
}
